﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace CPPEI.Coolzon.UI.XProperty.Converters
{
    /// <summary>
    /// 画刷转换器
    /// 将 <SolidBrush Color="#FF00FF00"/> 这种配置转换成画刷
    /// </summary>
    public class XBrushConverter : IPropertyValueConverter
    {
        public object Convert(ConvertContext context, Metadata.ValueNode valueNode)
        {
            if (valueNode.Name.Equals("SolidBrush"))
            {
                string colorString = valueNode.Attributes["Color"];
                if (!string.IsNullOrEmpty(colorString))
                {
                    SolidColorBrush scb = new SolidColorBrush((Color)ColorConverter.ConvertFromString(colorString));
                    return new BrushEx(scb);
                }
            }
            else if (valueNode.Name.Equals("ImageBrush"))
            {
                string sourceString = valueNode.Attributes["Source"].Replace(".\\", context.SolutionDirectory);
                if (!string.IsNullOrEmpty(sourceString))
                {
                    BitmapImage bitmapImage = null;

                    FileInfo file = new FileInfo(sourceString);
                    if (file != null && file.Exists)
                    {
                        using (FileStream fileStream = File.Open(file.FullName, FileMode.Open, FileAccess.Read))
                        {
                            using (BinaryReader binReader = new BinaryReader(fileStream))
                            {
                                byte[] bytes = binReader.ReadBytes((int)file.Length);

                                bitmapImage = new BitmapImage();
                                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                                bitmapImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                                bitmapImage.BeginInit();
                                bitmapImage.StreamSource = new MemoryStream(bytes);
                                bitmapImage.EndInit();
                            }
                        }
                    }
                    ImageBrush scb = new ImageBrush(bitmapImage);
                    return new BrushEx(scb, sourceString);
                }
            }
            else if (valueNode.Name.Equals("LinearGradientBrush"))
            {
                LinearGradientBrush lgb = new LinearGradientBrush();


                string strStartPoint = valueNode.Attributes["StartPoint"];
                string strEndPoint = valueNode.Attributes["EndPoint"];
                if (!string.IsNullOrEmpty(strStartPoint) && !string.IsNullOrEmpty(strEndPoint))
                {
                    string[] startPoints = strStartPoint.Split(',');
                    string[] endPoints = strEndPoint.Split(',');

                    lgb.StartPoint = new System.Windows.Point(double.Parse(startPoints[0]), double.Parse(startPoints[1]));
                    lgb.EndPoint = new System.Windows.Point(double.Parse(endPoints[0]), double.Parse(endPoints[1]));
                }

                foreach (Metadata.ValueNode vN in valueNode.ValueNodes)
                {
                    if (!string.IsNullOrEmpty(vN.Attributes["Color"]))
                    {
                        double offset = 0.0;
                        if (vN.Attributes.ContainsKey("Offset"))
                        {
                            double.TryParse(vN.Attributes["Offset"], out offset);
                        }

                        GradientStop gs = new GradientStop((Color)ColorConverter.ConvertFromString(vN.Attributes["Color"]), offset);
                        lgb.GradientStops.Add(gs);
                    }
                }
                return new BrushEx(lgb);
            }
            return null;
        }

        public Metadata.ValueNode ConvertBack(ConvertContext context, object value)
        {
            if(value == null)
            {
                return null;
            }
            Metadata.ValueNode vNode = null;
            BrushEx brushEx = value as BrushEx;
            if (brushEx.Brush is SolidColorBrush)
            {
                vNode = new Metadata.ValueNode("SolidBrush");
                vNode.Attributes = new Dictionary<string, string>();
                Color color = (Color)ColorConverter.ConvertFromString(System.Convert.ToString(brushEx.Brush));
                string colorString = color.ToString();
                vNode.Attributes.Add("Color", colorString);
            }
            else if (brushEx.Brush is ImageBrush)
            {
                vNode = new Metadata.ValueNode("ImageBrush");
                vNode.Attributes = new Dictionary<string, string>();
                ImageBrush imageBrush = (ImageBrush)brushEx.Brush;

                vNode.Attributes.Add("Source", brushEx.Path.Replace("/", "\\").Replace(context.SolutionDirectory, ".\\"));
                vNode.Attributes.Add("TileMode", imageBrush.TileMode.ToString());
                vNode.Attributes.Add("Stretch", imageBrush.Stretch.ToString());
            }
            else if (brushEx.Brush is LinearGradientBrush)
            {
                vNode = new Metadata.ValueNode("LinearGradientBrush");
                vNode.Attributes = new Dictionary<string, string>();
                LinearGradientBrush brush = (LinearGradientBrush)brushEx.Brush;
                vNode.Attributes.Add("StartPoint", brush.StartPoint.ToString());
                vNode.Attributes.Add("EndPoint", brush.EndPoint.ToString());

                foreach (GradientStop gs in brush.GradientStops)
                {
                    Metadata.ValueNode vGs = new Metadata.ValueNode("GradientStop");
                    vGs.Attributes = new Dictionary<string, string>();
                    vGs.Attributes.Add("Color", gs.Color.ToString());
                    vGs.Attributes.Add("Offset", gs.Offset.ToString());

                    if (vNode.ValueNodes == null)
                        vNode.ValueNodes = new List<Metadata.ValueNode>();
                    vNode.ValueNodes.Add(vGs);
                }
            }
            return vNode;
        }
    }
}
